import axios from 'axios'
import { getToken } from './auth'
import store from '../store'
import { Toast } from 'vant'
const baseURL: any = import.meta.env.DEV ? '' : import.meta.env.VITE_APP_BASEURL

const service = axios.create({
  baseURL,
  timeout: 5000 // request timeout
})
// 发起请求之前的拦截器
service.interceptors.request.use(
  (config) => {
    // 如果有token 就携带tokon
    Toast.loading({
      forbidClick: true,
      duration: 0
    })
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    config.headers['X-Ticket'] = store.getters.ticket || new Date().getTime()
    // config.headers["Dev-ID"] = "weixin";
    // config.headers["Client-Platform"] = "diangongbao-H5";
    return config
  },
  (error) => Promise.reject(error)
)
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // Toast.clear()
    const res = response.data
    store.commit('app/SET_TICKET', res.ticket)
    if (response.status !== 200) {
      Toast({
        message: '网络异常',
        position: 'bottom'
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code * 1 === 10005) {
      Toast({
        message: res.message,
        position: 'bottom'
      })

      store.dispatch('user/loginOut').then(() => {
        setTimeout(() => {
          location.reload()
        }, 200)
        return Promise.reject(new Error(res.message || 'Error'))
      })
    } else if (!res.success) {
      Toast({
        message: res.message,
        position: 'bottom'
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    Toast({
      message: '网络异常',
      position: 'bottom'
    })
    return Promise.reject(error)
  }
)
export default service
